// src/pages/catering/goodsList/goodsList.js
import getIn from '../../../../../yali-sdk/utils/getIn';
import goodsListQuery from '../../../../../yali-sdk/business/catering/goodsListQuery';
import getGoodsCartQuery from '../../../../../yali-sdk/business/catering/getGoodsCartQuery';
import cartDetailQuery from '../../../../../yali-sdk/business/catering/cartDetailQuery';
import cartEmptyQuery from '../../../../../yali-sdk/business/catering/cartEmptyQuery';
import { updateNum, payDescText } from '../../../../../yali-sdk/business/catering/constrants';
import numberToWeekDay from '../../../../../yali-sdk/utils/numberToWeekDay';
import { getImagePath, showFail, showSuccess } from '../../../../config/common';
import { SUCCESS } from '../../../../../yali-sdk/utils/success';
import { FAIL } from '../../../../../yali-sdk/utils/fail';
import { CATERING_CREAT_ORDER, COUPON_LIST_PATH, CATERING_PRODUCT_DETAIL, POP_GOODS_LIST, CATERING_SHOP_COMMENT_LIST } from '../../../../pages/pathUrl';
import fetchShopDetail from '../../../../../yali-sdk/business/shop/fetchShopDetail';
import { addNotifier, removeNotifier, notify } from '../../../../../yali-sdk/utils/NotifyRegistryCenter';
const window_height = getIn(getApp(), ['globalData', 'window_height']);
const window_width = getIn(getApp(), ['globalData', 'window_width']);
Page({
  data: {
    productList: [],
    coupon: { 
      total: 0,
      detail: [],
    },
    totalPrice: 0,// 总价格
    totalCount: 0, // 总商品数
    carArray: [],
    minPrice: 0,//起送价格
    payDesc: '去结算', // 右下角结算文字
    deliveryPrice: 0,//配送費
    fold: false,// 购物车开关
    shop_detail: {}, // 门店基本信息
    showAttr: false, // 选择属性弹窗
    selectPro: {}, // 有属性选择的产品（弹出属性弹窗后的数据）
    cate_id: null,
    newProduct: []
  },
  onLoad(options) {
    const token = getIn(getApp(), ['globalData', 'token']);
    this.multiShopList({ token, ...options });
    this.fetchData({ token, is_recommend: true });
    this.fetchData({ token });
    this.fetchCart(token);
    addNotifier('UPDATE_GOODDLIST_DATA', () => {
      this.fetchData({ token });
      this.fetchCart(token);
    }, this);
    
  },
  onUnload() {
    removeNotifier('UPDATE_GOODDLIST_DATA');
  },
  // onShow () {
  //   this.fetchData({token:this.data.token });
  //   this.fetchCart(this.data.token);
  // },
  // 获取门店详情
  multiShopList(params) {
    const cate_id = getIn(params, ['cate_id']);
    const id = getIn(params, ['id']);
    wx.showNavigationBarLoading()
    global.ActionDispatcher.execute(fetchShopDetail, params, (code, res) => {
      let shop_detail = { id };
      if (code == 'SUCCESS') {
        wx.hideNavigationBarLoading()
        shop_detail = res.data;
        shop_detail.color = shop_detail.template == 1 ? '#ee2b47' : shop_detail.template == 2 ? '#0298ef' : '#ff8400';
        wx.setNavigationBarTitle({
          title: shop_detail.name
        })
      } else if (code == 'FAIL') {
        console.log('调用失败')
      } 
      this.setData({
        token: params.token,
        shop_detail,
        cate_id
      });
    });
  },
  // 访问列表数据
  fetchData(parma) {
    const token = parma.token || getIn(getApp(), ['globalData', 'token']);
    const id = getIn(this.options, ['id']);
    const params = parma.is_recommend ? { token, shop_id:id, is_recommend: parma.is_recommend } : { token, shop_id:id };
    global.ActionDispatcher.execute(goodsListQuery, params, (code, res) => {
      if (code == SUCCESS) {
        wx.stopPullDownRefresh();
        wx.hideLoading();
        const productList = getIn(res.data, ['list']);
        if (parma.is_recommend) {
          // 推荐产品列表
          const newProduct = this.formatArray(productList);
          this.setData({ newProduct });
        } else {
          // 产品列表
          this.setData({ productList });
        }
      } else if (code == FAIL) {
        wx.stopPullDownRefresh();
        wx.hideLoading();
      }
    });
  },
  // 购物车数据
  fetchCart(token) {
    token = token || getIn(getApp(), ['globalData', 'token']);
    const id = getIn(this.options, ['id']);
    global.ActionDispatcher.execute(cartDetailQuery, { token, shop_id:id }, (code, res) => {
      if (code == SUCCESS) {
        const carArray = getIn(res.data, ['list']) || [];
        const totalPrice = getIn(res.data, ['total_price']) || 0;
        const totalCount = getIn(res.data, ['total_num']) || 0;
        const payDesc = payDescText(totalPrice, this.data.minPrice);
        this.setData({ carArray, totalPrice: totalPrice, totalCount, payDesc });
      } if (code == FAIL) {
        const payDesc = payDescText(this.data.totalPrice, this.data.minPrice);
        this.setData({ payDesc });
      }
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    const token = getIn(getApp(), ['globalData', 'token']);
    this.fetchData({ token, is_recommend: true });
    this.fetchData({ token });
    this.fetchCart(token);
  },
  //清空回收站
  clearCart (e) {
    const token = getIn(getApp(), ['globalData', 'token']);
    const shop_id = getIn(this.data, ['shop_detail', 'id']);
    global.ActionDispatcher.execute(cartEmptyQuery, { token, shop_id }, (code, res) => {
      if (code == SUCCESS) {
        this.fetchData(this.data.shop_detail);
        this.fetchCart(this.data.shop_detail);
        this.setData({ fold: false });
        showSuccess('操作成功');
      } else if(code == FAIL) {
        showFail('操作失败');
      }
    })
  },
  // 处理newProduct数组
  formatArray(arr) {
    let begin = 0,
      end = begin + 4;
    let result = [],
      arrLength = arr.length;
    if (end >= arrLength) result.push(arr);
    while (end < arrLength) {
      result.push(arr.slice(begin, end));
      begin = begin + 8;
      end = begin + 8;
      if (end > arrLength) {
        end = arrLength;
        result.push(arr.slice(begin, end));
        break;
      }
    }
    return result;
  },
  //修改产品购物车数量
  modifiesCart(e) {
    const { productList, carArray } = this.data;
    const id = e.currentTarget.id || e.detail.id;
    const num = getIn(e.currentTarget.dataset, ['num']) || e.detail.num || 0;
    const token = getIn(getApp(), ['globalData', 'token']);
    const shop_id = getIn(this.data.shop_detail, ['id']);
    const group_attr = getIn(e.detail, ['group_attr']);
    const callback = getIn(e.detail, ['callback']);
    const params = group_attr ? { token, shop_id, product_id: id, num: Number(num), group_attr } : { token, shop_id, product_id: id, num: Number(num) };
    const obj = { ...updateNum([{ product_list: productList }], Number(num), id, group_attr) }
    this.setData({ productList: obj.product[0].product_list, selectPro: obj.selectPro });
    global.ActionDispatcher.execute(getGoodsCartQuery, params, (code, res) => {
      if (code == SUCCESS) {
        const carArray = getIn(res.data, ['list']);
        const totalPrice = getIn(res.data, ['total_price']);
        const totalCount = getIn(res.data, ['total_num']);
        const payDesc = payDescText(totalPrice, this.data.minPrice);
        if (totalCount == 0) {
          this.setData({ fold: false });
        }
        this.setData({ carArray, totalPrice, totalCount });
      } else if (code == FAIL) {
        showFail(res.msg);
        if (Number(res.code) == -101) {
          const obj = { ...updateNum([{ product_list: productList }], 0, id, group_attr) };
          this.setData({ productList: obj.product[0].product_list, selectPro: obj.selectPro });
        } else {
          const reset_num = getIn(res.data, ['num']);
          const reset_id = getIn(res.data, ['id']);
          const reset_attr_group_id = getIn(res.data, ['attr_group_id']);
          const obj = { ...updateNum([{ product_list: productList }], Number(reset_num), id, reset_attr_group_id) };
          this.setData({ productList: obj.product[0].product_list, selectPro: obj.selectPro });
        }
      }
    });
  },
  //结算
  pay() {
    if (this.data.totalPrice == 0 || this.data.totalPrice < this.data.minPrice) {
      return;
    }
    const color = getIn(this.data.shop_detail, ['color']);
    const template = getIn(this.data.shop_detail, ['template']);
    const shop_id = getIn(this.data.shop_detail, ['id']);
    const queryString = `color=${color}&shop_id=${shop_id}&template=${template}`;
    global.navigateHelper && global.navigateHelper.navigateTo({ pathname: CATERING_CREAT_ORDER, queryString });
  },
  //弹起购物车
  toggleList () {
    if (this.data.totalCount > 0) {
      this.setData({ fold: true });
    }
  },
  // 关闭购物车
  hideCartCallBack(e) {
    this.setData({ fold: e.detail.fold });
  },
  // 选择规格弹出窗
  selectAttr(e) {
    const { productList } = this.data;
    const cate_id = getIn(e.currentTarget, ['dataset', 'cate_id']);
    const id = getIn(e.currentTarget, ['id']);
    const selectCate = productList.find(x => x.id == cate_id);
    const selectPro = selectCate && selectCate.product_list.find(t => t.id == id);
    this.setData({ showAttr: true, selectPro });
  },
  // 关闭属性框回调
  hideAttrBoxCallBack(e) {
    this.setData({ showAttr: e.detail.showAttr, selectPro: {} });
  },
  // 跳转详细页
  toDetail(e) {
    const id = getIn(e.currentTarget, ['id']);
    const { shop_detail } = this.data;
    const queryString = `id=${id}&color=${shop_detail.color}&shop_id=${shop_detail.id}template=${shop_detail.template}`;
    global.navigateHelper && global.navigateHelper.navigateTo({ pathname: CATERING_PRODUCT_DETAIL, queryString });
  },
  // 跳转产品列表页
  toGoodsList() {
    const queryString = `shop_detail=${JSON.stringify(this.data.shop_detail)}`;
    global.navigateHelper && global.navigateHelper.navigateTo({ pathname: POP_GOODS_LIST, queryString });
  },
  // 查看地图
  openMap() {
    const { shop_detail: { address } } = this.data;
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        const latitude = address.lat
        const longitude = address.lng
        wx.openLocation({
          latitude,
          longitude,
          scale: 28
        })
      }
    })
  },
  // 打电话
  makePhoneCall() {
    const { shop_detail } = this.data;
    wx.makePhoneCall({
      phoneNumber: shop_detail.tel
    })
  },
  // 跳转评论页列表
  toCommendList() {
    const { shop_detail } = this.data;
    const queryString = `color=${shop_detail.color}&shop_id=${shop_detail.id}`;
    global.navigateHelper && global.navigateHelper.navigateTo({ pathname: CATERING_SHOP_COMMENT_LIST, queryString });
  },
  // 拨打商家电话
  makePhone() {
    const { shop_detail } = this.data;
    wx.makePhoneCall({
      phoneNumber: shop_detail.tel
    })
  },
  // 查看地图
  openMap() {
    const { shop_detail: { address } } = this.data;
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        const latitude = address.lat
        const longitude = address.lng
        wx.openLocation({
          latitude,
          longitude,
          scale: 28
        })
      }
    })
  },
})